package com.example.common.mvi

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.example.common.base.BaseEvent
import com.example.common.base.BaseFragment
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

abstract class BaseMviFragment <T:ViewDataBinding>: BaseFragment<T>() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
       val view= super.onCreateView(inflater, container, savedInstanceState)

        EventBus.getDefault().register(this)
        return view
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun receiveEvent(event : BaseEvent){
        if (event != null && event.target==this::class.java.simpleName){
            handEvent(event)
        }
    }

    override fun onDestroyView() {
        EventBus.getDefault().unregister(this)
        super.onDestroyView()
    }

    override fun initData() {
        lifecycleScope.launch {
            sendViewIntent()
        }
    }

    override fun updateUI() {
        lifecycleScope.launch {
            lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED){
                collectUIState()
            }
        }
    }




    open fun handEvent(event: BaseEvent){

    }

    open suspend fun sendViewIntent(){

    }

    open suspend fun collectUIState(){

    }
}